import React, { useEffect, useState } from 'react';
import { Modal, Table, message, Button, Popconfirm } from 'antd';
import request from '@/utils/request';

const TemplateListModal = ({ visible, onCancel, onSelect }) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [deletingRow, setDeletingRow] = useState(null);

  const fetchList = () => {
    setLoading(true);
    request('/PDS/DataSetTemplateListNew', {
      method: 'GET',
    })
      .then((res) => {
        if (res.data.code === 200) {
          setData(res.data.data || []);
        } else {
          message.error(res.data.msg || '获取模版列表失败');
        }
      })
      .catch((err) => {
        message.error(err?.message || '获取模版列表失败');
      })
      .finally(() => setLoading(false));
  };

  // 单行删除方法
  const handleDeleteSingle = (template_id) => {
    setDeletingRow(template_id);
    request('/PDS/DataSetTemplateDeleteNew', {
      method: 'POST',
      data: {
        template_ids: [template_id],
      },
    })
      .then((res) => {
        if (res.data.code === 200) {
          message.success('删除成功');
          fetchList();
        } else {
          message.error(res.data.msg || '删除失败');
        }
      })
      .catch((err) => {
        message.error(err?.message || '删除失败');
      })
      .finally(() => setDeletingRow(null));
  };

  // 选择模版
  const handleSelect = (record) => {
    if (onSelect) {
      onSelect(record);
    }
    if (onCancel) {
      onCancel();
    }
  };

  useEffect(() => {
    if (visible) {
      fetchList();
    }
  }, [visible]);

  // columns数组移到组件内部
  const columns = [
    {
      title: '模版名称',
      dataIndex: 'template_name',
      key: 'template_name',
    },
    {
      title: '操作',
      key: 'action',
      align: 'center' as const,
      render: (_, record) => (
        <>
          <Button type="link" size="small" onClick={() => handleSelect(record)}>选择</Button>
          <Popconfirm
            title="确定要删除该模版吗？"
            onConfirm={() => handleDeleteSingle(record.template_id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger size="small" loading={deletingRow === record.template_id}>删除</Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  return (
    <Modal
      title="PDS模版列表"
      open={visible}
      onCancel={onCancel}
      footer={null}
      width={600}
    >
      <Table
        columns={columns}
        dataSource={data}
        rowKey="template_id"
        loading={loading}
        pagination={false}
        scroll={{ y: 400 }}
      />
    </Modal>
  );
};

export default TemplateListModal; 